﻿/*
____
 L|ypps Web controls for ASP.NET

Copyright (c) 2009 Alessandro Zifiglio, http://www.Typps.com
EMail: alessandro@Typps.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace Typps
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text.RegularExpressions;

    using Sgml;

    #region Enumerations

    public enum DtdSchema
    {
        XhtmlTransitional,
        XhtmlStrict,
        XhtmlFrameset,
    }

    #endregion Enumerations

    public class HtmlDtdParser
    {
        #region Fields

        const string dtdFolder = "Typps.Resources.Dtd.{0}";

        CaseFolding _caseFolding = CaseFolding.ToLower;
        Stream _dtdStream;
        bool _ignorePreTagContents = true;
        string[] _manifestResourceNamesCache = null;
        Dictionary<string, Stream> _mnemonicEntities = null;
        bool _prettyHtml = true;
        Dictionary<string, string> _replacementTagsList = null;
        DtdSchema _schema;

        #endregion Fields

        #region Constructors

        public HtmlDtdParser()
            : this(null,DtdSchema.XhtmlStrict)
        {
        }

        public HtmlDtdParser(DtdSchema schema)
            : this(null, schema)
        {
        }

        public HtmlDtdParser(string[] manifestResourceNamesCache, DtdSchema schema)
        {
            _manifestResourceNamesCache = manifestResourceNamesCache;
            if(_manifestResourceNamesCache==null)
                _manifestResourceNamesCache = typeof(HtmlDtdParser).Assembly.GetManifestResourceNames();
            _schema = schema;
        }

        #endregion Constructors

        #region Properties

        public CaseFolding CaseFolding
        {
            get { return _caseFolding; }
            set { _caseFolding = value; }
        }

        public Stream DtdStream
        {
            get { return _dtdStream; }
        }

        public bool IgnorePreTagContents
        {
            get { return _ignorePreTagContents; }
            set { _ignorePreTagContents = value; }
        }

        public Dictionary<string, Stream> MnemonicEntities
        {
            get
            {
                if (_mnemonicEntities == null)
                    _mnemonicEntities = new Dictionary<string, Stream>();
                return _mnemonicEntities;
            }
        }

        public bool PrettyHtml
        {
            get { return _prettyHtml; }
            set { _prettyHtml = value; }
        }

        public DtdSchema Schema
        {
            get { return _schema; }
            set { _schema = value; }
        }

        #endregion Properties

        #region Methods

        public ParsedSourceContent ParseHtml(string source)
        {
            Startup();

            if (IgnorePreTagContents)
                source = PreTagExtract(source);

            ParsedSourceContent content = new ParsedSourceContent { Success=true};
            using (SgmlReader r = new SgmlReader(DtdStream, MnemonicEntities))
            {
                r.SystemLiteral = string.Empty;
                using (r.InputStream = new StringReader(source))
                {
                    r.CaseFolding = CaseFolding.ToLower;
                    r.DocType = "html";
                    r.FormatHtml = PrettyHtml;
                    try
                    {
                        content.Source = r.ReadOuterXml();
                    }
                    catch (Exception e)
                    {
                        string errormessage = e.Message;
                        content.Success = false;
                        content.Source = source;//we couldn't make any fixes, quite unlikely but possible :|
                    }
                }
                content.FailureMessage = r.ErrorLog.ToString();
                r.ErrorLog.Close();
            }

            content.Source = PreTagAppend(content.Source);
            return content;
        }

        internal void Startup()
        {
            string schemaFileName = "xhtml1-strict.dtd";
            switch (Schema)
            {
                case DtdSchema.XhtmlFrameset:
                    schemaFileName = "xhtml1-frameset.dtd";
                    break;
                case DtdSchema.XhtmlTransitional:
                    schemaFileName = "xhtml1-transitional.dtd";
                    break;
            }
            _dtdStream = typeof(HtmlDtdParser).Assembly.GetManifestResourceStream(
                Helper.GetManifestResourceName(string.Format(dtdFolder, schemaFileName),_manifestResourceNamesCache));
            if (MnemonicEntities.Count == 0)
            {
                string[] entities = { "xhtml-lat1.ent", "xhtml-special.ent", "xhtml-symbol.ent" };
                foreach (string ent in entities)
                {
                    Stream s = typeof(HtmlDtdParser).Assembly.GetManifestResourceStream(
                    Helper.GetManifestResourceName(string.Format(dtdFolder, ent), _manifestResourceNamesCache));
                    MnemonicEntities.Add(ent, s);
                }
            }
        }

        private string PreTagAppend(string html)
        {
            string[] elements = new string[] { "<PRE", "</PRE>", "<SPAN", "</SPAN>", "<BR" };
            foreach (KeyValuePair<string, string> kvp in _replacementTagsList)
            {
                string value = kvp.Value;
                foreach (string elem in elements)
                    value = Regex.Replace(value, Regex.Escape(elem),
                                    elem.ToLower(), RegexOptions.IgnoreCase);
                html = html.Replace(kvp.Key, value);
            }
            return html;
        }

        /// <summary>
        /// Pre tags are excluded from markup validation since fixing of markup
        /// will eventually messup the formatting. The whole purpose of the pre
        /// tag is to retain formatting and is indeed undesired, so instead
        /// lets remove them prior to having the source processed by this sgml parser.
        /// While we are at it, let's also make some minimum fixes like improperly 
        /// closed br tag and let's also fix the casing of the pre element,
        /// and spans used in the markup insdie the pre
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private string PreTagExtract(string html)
        {
            _replacementTagsList = new Dictionary<string, string>();
            int replacementId = 0;
            int preStart = html.IndexOf("<pre", StringComparison.OrdinalIgnoreCase);
            string tagKey = "<div id=\"typpsreplacedpre-{0}\"></div>";
            while (preStart != -1)
            {
                int preEnd = html.IndexOf("</pre>", StringComparison.OrdinalIgnoreCase);
                if (preEnd != -1)
                {
                    string key = string.Format(tagKey, replacementId);
                    string extracted = html.Substring(preStart, (preEnd + 6) - preStart);
                    _replacementTagsList.Add(key, extracted.Replace("<br>", "<br />"));
                    html = html.Replace(extracted, key);
                    ++replacementId;
                }
                preStart = html.IndexOf("<pre", StringComparison.OrdinalIgnoreCase);
                if (preStart != -1)
                {
                    preEnd = html.IndexOf("</pre>", StringComparison.OrdinalIgnoreCase);
                    if (preEnd == -1)
                        preStart = -1;
                }
            }
            return html;
        }

        #endregion Methods
    }

    public class ParsedSourceContent
    {
        #region Properties

        public string FailureMessage
        {
            get; set;
        }

        public string Source
        {
            get; set;
        }

        public bool Success
        {
            get; set;
        }

        #endregion Properties
    }
}